'use strict';
/**
 * 获取随机数
 * @param {Number} min 最小值
 * @param {Number} max 最大值
 * @return {Number} 随机数
 */
const random = (min, max) => {
  return parseInt(Math.random() * (max - min) + min);
};
/**
 * 获取一个随机code码
 * @param {number} len 随机数的长度
 * @return {string} 随机的数字
 */
const randomCode = len => {
  let num = '';
  while (num.length < len) {
    num += random(0, 10);
  }
  return num;
};

const arrayToTree = arr => {
  const tree = [];
  const arrJSON = {};

  arr.forEach(item => {
    arrJSON[item.id] = item;
  });

  arr.forEach(item => {
    const parent = arrJSON[item.parent_id];
    if (parent) {
      if (parent.children) {
        parent.children.push(item);
      } else {
        parent.children = [ item ];
      }
    } else {
      tree.push(item);
    }
  });

  return tree;
};

const getChildrenIds = (arr, id, flg = false) => {
  let ids = [];
  arr.forEach(item => {
    if (flg) {
      if (item.children) {
        ids = ids.concat(getChildrenIds(item.children, item.id, true));
      } else {
        ids.push(item.id);
      }
    } else {
      if (item.children) {
        if (item.id === id * 1) {
          ids = ids.concat(getChildrenIds(item.children, item.id, true));
        } else {
          ids = ids.concat(getChildrenIds(item.children, id));
        }
      }
    }
  });
  return ids;
};

module.exports = {
  random,
  randomCode,
  arrayToTree,
  getChildrenIds,
};
